from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.db.utils import IntegrityError
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from user.models import Player
from game.models import Robot


@csrf_exempt
def loginAction(request):
	username = request.POST.get("username")
	password = request.POST.get("password")
	user = authenticate(username=username, password=password)
	status = "error"
	if user is not None:
		login(request, user)
		status = ""
	return JsonResponse({"status": status})


def logoutAction(request):
	logout(request)
	return redirect('index')


def register(request):
	if request.user.is_authenticated():
		return redirect('index')
	else:
		return render(request, 'user/register.html', {})


@csrf_exempt
def registerAction(request):
	if request.user.is_authenticated():
		return redirect('index')
	else:
		status = ""
		try:
			username = request.POST.get("username")
			email = request.POST.get("email")
			password = request.POST.get("password")
			# 创建新用户
			user = User.objects.create_user(username, email, password)
			player = Player()
			player.user = user
			player.save()
			user.player = player
			user.save()
			# 登录新用户
			user = authenticate(username=username, password=password)
			login(request, user)
		except IntegrityError:
			status = "用户名已存在"
		finally:
			return JsonResponse({"status": status})


@login_required
def index(request):
	robots = Robot.objects.filter(user=request.user)
	return render(request, "user/index.html", {"robots": robots})